package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.common.RedisConstants;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 张一恒
 * @version 1.0
 * @description: TODO
 * @date 2022/11/17 23:09
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session中的用户
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //从redis获取用户信息
        String userMap = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> users = stringRedisTemplate.opsForHash()
                .entries(userMap);
        //判断用户是否存在
        if (users.isEmpty()) {
            return true;
        }

        //map转成dto
        UserDTO userDTO = BeanUtil.fillBeanWithMap(users, new UserDTO(), false);
        //存在保存用户到当前线程
        UserHolder.saveUser(userDTO);
        //设置有效期
        stringRedisTemplate.expire(userMap,RedisConstants.LOGIN_USER_TLL, TimeUnit.MINUTES);

        return true;
    }

    //后置拦截器
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        //删除user信息释放资源
        UserHolder.removeUser();
    }
}
